﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.IO;
using CommunitySystem.JinShengService;
using EHR.Common;

namespace CommunitySystem.PageView.晋升管理
{
    public partial class PromotCheckWindow : ChildWindow
    {
       public ObservableCollection<JinShen_MainInfo> entitys = new ObservableCollection<JinShen_MainInfo>();
       public bool ReturnTrue = false;


        public JinShengService.JinShen_MainInfo _mainInfo = null;
        private PublicOfficialSelectionService.PublicOfficialSelectionServiceClient downLoadClient = null;
        List<byte> fileContent = new List<byte>();
        private JinShengService.JinShen_MainInfo_Check checkEntity = null;
        private JinShengService.JinShengServiceClient jinShenClient = null;
        public PromotCheckWindow(JinShengService.JinShen_MainInfo mainInfo)
        {
            InitializeComponent();
            _mainInfo = mainInfo;

            hlb.Visibility = System.Windows.Visibility.Visible;
            wp.Visibility = System.Windows.Visibility.Visible;

            jinShenClient = new JinShengService.JinShengServiceClient();
            
            downLoadClient = new PublicOfficialSelectionService.PublicOfficialSelectionServiceClient();
            downLoadClient.DownLoadFileCompleted += (sender, e) =>
            {
                var down = e.Result;
                fileContent.AddRange(down.Content);
                if (down.HasFinished == true)
                {
                    var stream = e.UserState as Stream;
                    stream.Write(fileContent.ToArray(), 0, fileContent.Count);
                    stream.Dispose();
                    stream.Close();
                    SilverlightMessageBoxLibrary.Message.InfoMessage("下载完毕!");
                }
                else
                {
                    down.StartPosition += down.Lenght;
                    downLoadClient.DownLoadFileAsync(down, e.UserState);
                }
            };
           
            ///前面是方案审核，后面是候选人审核
            if (_mainInfo.Status == JinShenConst.STATUS_Solution_Submit || _mainInfo.Status == JinShenConst.STATUS_CandidateChecking)//新增一条审核信息
            {
                checkEntity = new JinShengService.JinShen_MainInfo_Check() { MainID = mainInfo.ID };
                DataBinding();
            }
            else//编辑一条审核信息
            {
                jinShenClient.GetMainInfo_CheckCompleted += (sender, e) =>
                {
                    checkEntity = e.Result.FirstOrDefault();
                    DataBinding();
                };
                jinShenClient.GetMainInfo_CheckAsync("MainID=" + mainInfo.ID + "  order by id desc");
            }

         
            jinShenClient.SaveJinShenMainInfoCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    
                    jinShenClient.SaveMainInfo_CheckAsync(checkEntity);
                }
                else
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("保存失败");
                }
            };
            //保存审核相关记录
            jinShenClient.AddJinShen_SHJLDetailCompleted += (ss, ee) =>
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功");
                this.DialogResult = true;
            };
            jinShenClient.SaveMainInfo_CheckCompleted += (sender1, e1) =>
            {
                if (e1.Error == null && e1.Result == true)
                {
                    //SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功");
                    //this.DialogResult = true;
                    JinShen_SHJLDetail shjl = new JinShen_SHJLDetail();
                    shjl.Name = "方案审核";
                    shjl.JSMID = _mainInfo.MId;
                    shjl.Status = _mainInfo.Status;
                    shjl.BLDate = shjl.CreateDate = DateTime.Now;
                    shjl.CreateUser = Session.LoginUser.LoginName;
                    if (!string.IsNullOrEmpty(shjl.Name))
                        jinShenClient.AddJinShen_SHJLDetailAsync(shjl, _mainInfo);
                }
                else
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("保存失败");
                }
            };
            
        }
        private bool Newjinsheng = false;
        private bool _isck = false;
        public PromotCheckWindow(JinShengService.JinShen_MainInfo mainInfo,bool isNew,bool isck)
        {
            InitializeComponent();
            _isck = isck;
            Newjinsheng = isNew;
            if (isck)
            {
                this.OKButton.Visibility = Visibility.Collapsed;
                this.btnAdd.Visibility = Visibility.Collapsed;
            }

            if (!isNew)
            {
                mainInfoGrid.Height = 180;
                mainInfoGrid.RowDefinitions[5].Height = new GridLength(0);
            }
            this.hlb.Visibility = Visibility.Collapsed;

            _mainInfo = mainInfo;
          
            jinShenClient = new JinShengService.JinShengServiceClient();

            downLoadClient = new PublicOfficialSelectionService.PublicOfficialSelectionServiceClient();
            downLoadClient.DownLoadFileCompleted += (sender, e) =>
            {
                var down = e.Result;
                fileContent.AddRange(down.Content);
                if (down.HasFinished == true)
                {
                    var stream = e.UserState as Stream;
                    stream.Write(fileContent.ToArray(), 0, fileContent.Count);
                    stream.Dispose();
                    stream.Close();
                    SilverlightMessageBoxLibrary.Message.InfoMessage("下载完毕!");
                }
                else
                {
                    down.StartPosition += down.Lenght;
                    downLoadClient.DownLoadFileAsync(down, e.UserState);
                }
            };

            ///前面是方案审核，后面是候选人审核
            if (_mainInfo.Status == JinShenConst.STATUS_Solution_Submit || _mainInfo.Status == JinShenConst.STATUS_CandidateChecking)//新增一条审核信息
            {
                checkEntity = new JinShengService.JinShen_MainInfo_Check() { MainID = mainInfo.ID };
                DataBinding();
            }
            else//编辑一条审核信息
            {
                jinShenClient.GetMainInfo_CheckCompleted += (sender, e) =>
                {
                    checkEntity = e.Result.FirstOrDefault();
                    DataBinding();
                };
                jinShenClient.GetMainInfo_CheckAsync("MainID=" + mainInfo.ID + "  order by id desc");
            }


            jinShenClient.SaveJinShenMainInfoCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {

                    jinShenClient.SaveMainInfo_CheckAsync(checkEntity);
                }
                else
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("保存失败");
                }
            };
            //保存审核相关记录
            jinShenClient.AddJinShen_SHJLDetailCompleted += (ss, ee) =>
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功");
                ReturnTrue = true;
                this.DialogResult = true;
            };
            jinShenClient.SaveMainInfo_CheckCompleted += (sender1, e1) =>
            {
                if (e1.Error == null && e1.Result == true)
                {
                    //SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功");
                    //ReturnTrue = true;
                    //this.DialogResult = true;
                    JinShen_SHJLDetail shjl = new JinShen_SHJLDetail();
                    if(!Newjinsheng)  shjl.Name = "方案审核";
                    else shjl.Name = "人员审核";
                    shjl.JSMID = _mainInfo.MId;
                    shjl.Status = _mainInfo.Status;
                    shjl.BLDate = shjl.CreateDate = DateTime.Now;
                    shjl.CreateUser = Session.LoginUser.LoginName;
                    if (!string.IsNullOrEmpty(shjl.Name))
                        jinShenClient.AddJinShen_SHJLDetailAsync(shjl, _mainInfo);
                }
                else
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("保存失败");
                    ReturnTrue = false;
                }
            };

        }

        private void DataBinding()
        {
           
            mainInfoGrid.DataContext = _mainInfo;
            dcbPromotionType.SelectedValue = _mainInfo.PromotType;
            //if (_mainInfo.PromotType.Equals("竞争上岗"))
            //{
                //hlb.Visibility = System.Windows.Visibility.Visible;
                //wp.Visibility = System.Windows.Visibility.Visible;
                foreach (var attach in _mainInfo.Attachment)
                {
                    StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal, };
                    HyperlinkButton hlbFile = new HyperlinkButton() { Content = attach.realname, DataContext = attach };
                    sp.Children.Add(hlbFile);
                    hlbFile.Click += (sender, e) =>
                    {
                        string extend =  attach.realname.Split('.').LastOrDefault();
                        var openFile = new SaveFileDialog() { Filter = string.Format("{0}|*.{0}", extend) };
                        if (openFile.ShowDialog() == true)
                        {
                            fileContent.Clear();
                            downLoadClient.DownLoadFileAsync(new PublicOfficialSelectionService.DownLoadFile()
                            { PathKey = "file", HasFinished = false, Lenght = 1600, FileName = attach.filename, StartPosition = 0 }, openFile.OpenFile());
                        }
                    };
                    wp.Children.Add(sp);
                }
            //}
            //else
            //{
            //    hlb.Visibility = System.Windows.Visibility.Collapsed;
            //    wp.Visibility = System.Windows.Visibility.Collapsed;
            //}
            if (checkEntity.IsPass == true)
            {
                dcbAgree.SelectedValue = "同意";
            }
            else if (checkEntity.IsPass == false)
            {
                dcbAgree.SelectedValue = "不同意";
            }
            if (_mainInfo.Status == JinShenConst.STATUS_CandidateCheck_UnPass || _mainInfo.Status == JinShenConst.STATUS_CandidateCheck_Pass || _mainInfo.Status == JinShenConst.STATUS_CandidateChecking)
            {
                #region
                //mainInfoGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(), MaxHeight = 120 });

                //TextBlock tb = new TextBlock() { Text = "候选人：", HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, Margin =new Thickness(8)};
                //Grid.SetRow(tb, 5);
                //Grid.SetColumn(tb, 0);
                //var temp = mainInfoGrid.Resources;
                //ListBox lb = new ListBox() { Height=140, Margin = new Thickness(8, 4, 0, 0), DisplayMemberPath = "Name" };
                ////lb.ItemTemplate = temp["display"] as DataTemplate;

                //Grid.SetRow(lb, 5);
                //Grid.SetColumn(lb, 1);
                //Grid.SetColumnSpan(lb, 2);

    
                
                //Image imgAdd = new Image() { Cursor = Cursors.Hand, Margin = new Thickness(-70, 5, 8, 8), Height = 27, Width = 27,VerticalAlignment=VerticalAlignment.Top };
                //imgAdd.Source = new System.Windows.Media.Imaging.BitmapImage(
                //    new Uri("/CommunitySystem;component/Images/ViewDesign/add.png",
                //        UriKind.RelativeOrAbsolute));
               // imgAdd.MouseLeftButtonDown += new MouseButtonEventHandler(imgAdd_MouseLeftButtonDown);
                //Grid.SetRow(imgAdd, 5);
                //Grid.SetColumn(imgAdd, 3);

                //lb.ItemsSource = _mainInfo.Details;
                //this.Title = "人员审核";
                //mainInfoGrid.Height += 150;
                //mainInfoGrid.Children.Add(tb);
                //mainInfoGrid.Children.Add(lb);
                //mainInfoGrid.Children.Add(imgAdd);
                #endregion
                lbDetail.ItemsSource = _mainInfo.Details;
            }
            if (_isck) lbDetail.ItemsSource = _mainInfo.Details;
            tbDSC.DataContext = checkEntity;
        }

        void imgAdd_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            AddEmpWindow wind = new AddEmpWindow((int)_mainInfo.OrgID, _mainInfo,true);
            wind.Show();
            wind.Closed += (sender1, e1) =>
            {
                if (wind.DialogResult == true && wind.SelectItems != null)
                {
                    if (_mainInfo.Details == null)
                        _mainInfo.Details = new System.Collections.ObjectModel.ObservableCollection<JinShengService.JinShen_DetailInfo>();
                    foreach (var emp in wind.SelectItems)
                    {
                        if (_mainInfo.Details.Where(c => c.EmpBasicID == emp.ID).Count() <= 0)
                        {
                            if (string.IsNullOrEmpty(emp.Gender))//破格
                            {
                                _mainInfo.Details.Add(new JinShengService.JinShen_DetailInfo() { EmpBasicID = emp.ID, Name = emp.Name, IsPoGe = false });
                            }
                            else
                            {
                                _mainInfo.Details.Add(new JinShengService.JinShen_DetailInfo() { EmpBasicID = emp.ID, Name = emp.Name, IsPoGe = true });
                            }
                        }
                        else
                        {
                            SilverlightMessageBoxLibrary.Message.InfoMessage(emp.Name + "已存在，不能重复添加");
                        }
                    }
                }
            };
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if (Validate())
            {
                if (checkEntity.IsPass == false)
                    _mainInfo.DSC = checkEntity.DSC;
                else
                    _mainInfo.DSC = "";

                if (_mainInfo.Status == JinShenConst.STATUS_CandidateCheck_UnPass || _mainInfo.Status == JinShenConst.STATUS_CandidateCheck_Pass || _mainInfo.Status == JinShenConst.STATUS_CandidateChecking)
                {
                    if (checkEntity.IsPass == true)
                    {
                        _mainInfo.Status = JinShenConst.STATUS_CandidateCheck_Pass;
                    }
                    else if (checkEntity.IsPass == false)
                    {
                        _mainInfo.Status = JinShenConst.STATUS_CandidateCheck_UnPass;
                    }
                }
                else
                {
                    if (checkEntity.IsPass == true)
                    {
                        _mainInfo.Status = JinShenConst.STATUS_SolutionPass;
                    }
                    else if (checkEntity.IsPass == false)
                    {
                        _mainInfo.Status = JinShenConst.STATUS_Solution_Retire;
                    }
                }

               
                    
                jinShenClient.SaveJinShenMainInfoAsync(_mainInfo);
            }
            
        }

        private bool Validate()
        {
            if (checkEntity.IsPass == null)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("请选择是否同意!");
                return false;
            }
            if (checkEntity.IsPass == false && string.IsNullOrEmpty(checkEntity.DSC))
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("请填写不同意理由!");
                return false;
            }

            //if (_mainInfo.Status == JinShenConst.STATUS_SolutionPass || _mainInfo.Status == JinShenConst.STATUS_CandidateCheck_UnPass)//方案审核通过 和人员审核不通过
            //{
            //    if (_mainInfo.PromotType == "竞争上岗")
            //    {
            //        if (_mainInfo.Details == null || _mainInfo.Details.Count <= 1)
            //        {
            //            SilverlightMessageBoxLibrary.Message.InfoMessage("竞争上岗至少有两位候选人!");
            //            return false;
            //        }
            //    }
            //    else
            //    {
            //        if (_mainInfo.Details == null || _mainInfo.Details.Count < 1)
            //        {
            //            SilverlightMessageBoxLibrary.Message.InfoMessage("竞争上岗至少有一位候选人!");
            //            return false;
            //        }
            //    }
            //}
            
            return true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void dcbAgree_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dcbAgree.SelectedValue != null && dcbAgree.SelectedValue.ToString().Equals("同意"))
            {
                checkEntity.IsPass = true;
                //checkEntity.DSC = "";
            }
            else if (dcbAgree.SelectedValue != null && dcbAgree.SelectedValue.ToString().Equals("不同意"))
            {
                checkEntity.IsPass = false;
            }

            if (checkEntity.IsPass == true)
            {
                //tbDSC.IsReadOnly = true;
            }
            else if (checkEntity.IsPass == false)
            {
               // tbDSC.IsReadOnly = false;
            }
        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var detail = (sender as Image).DataContext as CommunitySystem.JinShengService.JinShen_DetailInfo;
            if (detail != null)
            {
                _mainInfo.Details.Remove(detail);
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            AddEmpWindow wind = new AddEmpWindow((int)_mainInfo.OrgID, _mainInfo, true);
            wind.Show();
            wind.Closed += (sender1, e1) =>
            {
                if (wind.DialogResult == true && wind.SelectItems != null)
                {
                    if (_mainInfo.Details == null)
                        _mainInfo.Details = new System.Collections.ObjectModel.ObservableCollection<JinShengService.JinShen_DetailInfo>();
                    foreach (var emp in wind.SelectItems)
                    {
                        if (_mainInfo.Details.Where(c => c.EmpBasicID == emp.ID).Count() <= 0)
                        {
                            if (string.IsNullOrEmpty(emp.Gender))//破格
                            {
                                _mainInfo.Details.Add(new JinShengService.JinShen_DetailInfo() { EmpBasicID = emp.ID, Name = emp.Name, IsPoGe = false });
                            }
                            else
                            {
                                _mainInfo.Details.Add(new JinShengService.JinShen_DetailInfo() { EmpBasicID = emp.ID, Name = emp.Name, IsPoGe = true });
                            }
                        }
                        else
                        {
                            SilverlightMessageBoxLibrary.Message.InfoMessage(emp.Name + "已存在，不能重复添加");
                        }
                    }
                }
            };
        }
        /// <summary>
        /// listbox  人员详细信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            int empid =Convert.ToInt32((sender as HyperlinkButton).Tag);
            JSOtherEmpInfo view = new JSOtherEmpInfo(empid);
            view.Show();
        }
    }
}

